package com.effect.part1_ObjectCrateDestroy.item1;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by jon on 17-10-7.
 */

interface Service {
    //Service-specifice methods go here
}

interface  Provider{
    Service newService();
}

public class Services {
    private Services() { //Prevents instantiation( Item 4)
    }
    //Maps service names to services
    private  static  final Map<String,Provider> providers =
            new ConcurrentHashMap<>();
    public  static  final  String DEFAULT_PROVIDER_NAME = "<def>";
    //Provider registration API
    public  static void registerDefaultProvider(Provider p){
        registerProvider(DEFAULT_PROVIDER_NAME,p);
    }
    public  static void registerProvider(String name,Provider p){
        providers.put(name,p);
    }
    //Service access API
    public  static  Service newInstance(String name){
        Provider p = providers.get(name);
        if (p==null)
            throw  new IllegalArgumentException(
                    "No provider registered with name: " + name);
        return  p.newService();
    }
}
